package com.by.config;


import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

@Component
@Slf4j
public class RabbitMqUtils {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //高并发有序访问/范围查询
    ConcurrentNavigableMap<String, String> orderMap = new ConcurrentSkipListMap<String, String>();

    /**
     * bean实例化后  调用的初始化方法  只调用一次
     */
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (null==correlationData){
               log.info("消息发送失败:correlationData({}),ack({}),cause({})",correlationData,ack,cause);
                return;
            }
            if (ack){
                orderMap.remove(correlationData.getId());
                log.info("消息发送成功:correlationData({}),ack({}),cause({})",correlationData,ack,cause);
            }else {
                log.info("消息发送失败:correlationData({}),ack({}),cause({})",correlationData,ack,cause);
            }
        });
    }



    /**
     * 发送消息
     * @param message
     */
    public void sendMessage(String  message){
        String id = UUID.fastUUID().toString();
        orderMap.put(id,message);
        rabbitTemplate.send(Constant.EXCHANGE_NAME,Constant.ROUTING_KEY,new Message(message.getBytes()),new CorrelationData(id));
    }
    /**
     * 延迟发送消息
     *
     * @param msg      要延迟发送的消息
     * @param lazyTime 延迟时长 单位是ms
     */
    public void sendLazyMsg(String msg, long lazyTime) {
        MessageProperties properties = new MessageProperties();
        properties.setHeader("x-delay", lazyTime);
        rabbitTemplate.send(Constant.LAZY_EXCHANGE, Constant.LAZY_KEY, new Message(msg.getBytes(), properties));
    }

}
